const qiniu = require("qiniu")
const config = require('../config')

const mac = new qiniu.auth.digest.Mac(config.qiniu.AK, config.qiniu.SK)

const options = {
  scope: config.qiniu.bucket,
  expires: 3600 * 24 * 365
}

let putPolicy    = new qiniu.rs.PutPolicy(options),
    uploadToken  = putPolicy.uploadToken(mac),
    formUploader = new qiniu.form_up.FormUploader(new qiniu.conf.Config()),
    putExtra     = new qiniu.form_up.PutExtra();

const uploadToQiNiu = (key, localFile) => {
  return new Promise ((resolve, reject) => {
    formUploader.putFile(uploadToken, key, localFile, putExtra, (respErr, respBody, respInfo) => {
      if (respErr) reject(respErr)
      if (respInfo.statusCode == 200) {
        resolve({isError: false, src: config.qiniu.baseUrl + respBody.key});
      } else {
        console.log(respInfo.statusCode);
        console.log(respBody);
      }
    })
  })
}

module.exports = uploadToQiNiu
